package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.util.jwt.AESUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserInfo;
import com.cskaoyan.user.dto.UserLoginPostRequest;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.service.UserLoginService;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.Cookie;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * lsj 登录
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    RedissonClient redissonClient;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserConverterMapper userConverterMapper;

    private final String KAPTCHA_UUID="kaptcha_uuid";




    @Override
    public UserLoginResponse userLoginPost(UserLoginPostRequest request) {
        UserLoginResponse response = new UserLoginResponse();

        try {
            // 参数校验
            request.requestCheck();
            //查询verify表，查询用户是否激活
            Example example = new Example(UserVerify.class);
            example.createCriteria().andEqualTo("username",request.getUserName());
            List<UserVerify> userVerifies = userVerifyMapper.selectByExample(example);

            //是否存在该用户的信息
            if (userVerifies == null ) {
                response.setCode("500");
                response.setMsg("用户不存在");
                return response;
            }
            if (userVerifies.size() == 0) {
                response.setCode("500");
                response.setMsg("系统错误");
                return response;
            }
            //查询verify表，查询用户是否激活
            UserVerify userVerify = userVerifies.get(0);
            if (Objects.equals("N",userVerify.getIsVerify())){
                response.setCode("500");
                response.setMsg("账户未激活");
                return response;
            }
            //通过cookie查询验证码的UUID 从Redis里面获取验证码对象 判断验证码是否正确
            RBucket<String> bucket = redissonClient.getBucket(KAPTCHA_UUID + request.getUuid());
            String code = bucket.get();
            System.out.println("lsj  code = " + code);
            if(!StringUtils.isNotBlank(code) || !code.equalsIgnoreCase(request.getCaptcha())){
                response.setCode(UserRetCode.KAPTCHA_CODE_ERROR.getCode());
                response.setMsg(UserRetCode.KAPTCHA_CODE_ERROR.getMessage());
                return response;
            }
            //查询member表，判断是否存在和request信息符合的member
            Example ex = new Example(Member.class);
            AESUtil aesUtil = new AESUtil(request.getUserPwd());

            ex.createCriteria().andEqualTo("username",request.getUserName()).andEqualTo("password", aesUtil.encrypt());
            List<Member> members = memberMapper.selectByExample(ex);

            if (members == null || members.size() == 0) {
                response.setCode(UserRetCode.USERORPASSWORD_ERRROR.getCode());
                response.setMsg(UserRetCode.USERORPASSWORD_ERRROR.getMessage());
                return response;
            }

            Member member = members.get(0);
            response = userConverterMapper.converter(member);
            response.setCode(UserRetCode.SUCCESS.getCode());
            response.setMsg(UserRetCode.SUCCESS.getMessage());

            UserInfo userInfo = new UserInfo(member.getUsername(), member.getId());
            String info = JSON.toJSONString(userInfo);
            String token = JwtTokenUtils.builder().msg(info).build().creatJwtToken();
            response.setToken(token);

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }
}
